package com.nebrija.riif.model.resolver;

import com.nebrija.riif.model.RIIFPropertiesContainer;
import com.nebrija.riif.model.Util;

public class ConditionalOpResolver {
	public static final String QUESTION_MARK="?";
	public static final String COLON=":";
	// condition, pre, post
	public Object resolve(String formula, RIIFPropertiesContainer c){
		int qmarkIndex = formula.indexOf(QUESTION_MARK);
		if(qmarkIndex==-1){
			return formula;
		}
		int colon = formula.indexOf(COLON, qmarkIndex);
		if(colon==-1){
			return formula;
		}
		String condition = formula.substring(0,qmarkIndex);
		String trueAction = formula.substring(qmarkIndex+1, colon);
		String falseAction = formula.substring(colon+1);
		LogicalResolver logical = new LogicalResolver();
		Object res = logical.resolve(condition, c);
		Object trueObj = Util.resolveFormula(trueAction, c);
		Object falseObj = Util.resolveFormula(falseAction, c);
		if(!(res instanceof Boolean)){
			return (res+QUESTION_MARK+trueObj.toString()+COLON+falseObj.toString());
		}
		Boolean boolRes = (Boolean) res;
		if(boolRes){
			return trueObj;
		}else{
			return falseObj;
		}
	}
}
